<template>
  <div class="production-plan-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">生产计划管理</h1>
      <div class="action-buttons">
        <el-button
          type="primary"
          @click="handleAdd"
          class="add-button"
          :class="{ 'scale-on-hover': true }"
        >
          <i class="el-icon-plus"></i> 新增计划
        </el-button>
        <el-button
          @click="handleExport"
          class="export-button"
          :class="{ 'scale-on-hover': true }"
        >
          <i class="el-icon-download"></i> 导出数据
        </el-button>
        <el-button
          type="danger"
          @click="handleDelete('批量删除')"
          :disabled="selectedRows.length === 0"
          >批量删除</el-button
        >
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        placeholder="搜索计划单号、主题或项目..."
        v-model="searchValue"
        suffix-icon="el-icon-search"
        class="search-input"
      ></el-input>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        border
        stripe
        highlight-current-row
        class="custom-table"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#303133',
          fontWeight: 'bold',
        }"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="productionPlanInfoId"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column
          prop="planNumber"
          label="计划单号"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="planTheme"
          label="计划主题"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="billDate" label="单据日期" width="130">
          <template #default="scope">
            <span>{{ formatDate(scope.row.billDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="businessType"
          label="物品概述"
          min-width="180"
        ></el-table-column>
        <el-table-column
          prop="relatedProject"
          label="关联项目"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="150"
        ></el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="
                handleDelete(scope.row.productionPlanInfoId, [
                  scope.row.materialCode,
                ])
              "
              style="margin-left: 5px"
              >删除</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="upd(scope.row.materialCode)"
              class="action-button view-btn"
              :class="{ 'fade-on-hover': true }"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 加载状态遮罩 -->
    <div v-if="loading" class="loading-mask">
      <el-loading-spinner></el-loading-spinner>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref, computed } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
// 状态管理
const state = reactive({
  loading: false,
  tableData: [],
  searchValue: "",
  total: 101,
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 20, 30, 50],
});

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 过滤后的数据
const filteredData = computed(() => {
  if (!state.searchValue) return state.tableData;
  const search = state.searchValue.toLowerCase();
  return state.tableData.filter(
    (item) =>
      item.planNo.toLowerCase().includes(search) ||
      item.planSubject.toLowerCase().includes(search) ||
      item.relatedProject.toLowerCase().includes(search)
  );
});
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});

// 模拟测试数据
const tableData = ref([]);
const searchProducts = () => {
  axios
    .get("http://localhost:5202/api/Log/GetProductionPlanInfo", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      tableData.value = res.data.data.list || [];
      form1.TotalCount = res.data.data.totalCount || 0;
      form1.PageCount = res.data.data.PageCount || 0;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
      ElMessage.error("获取物料列表失败，请检查网络或重试");
    });
};
// 修改选择处理逻辑（确保ID有效性）
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};
// 优化后的删除方法
const handleDelete = async (id: any, materialCode: any = []) => {
  try {
    let ids = [];
    let materialCodes = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.productionPlanInfoId);
      materialCodes = selectedRows.value.map((item) => item.materialCode);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      materialCodes = materialCode;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "ProductionPlans");
    params.append("TableId", "ProductionPlanInfoId");
    ids.forEach((id) => params.append("Ids", id.toString()));
    materialCodes.forEach((num) => params.append("MaterialCode", num));

    const res = await axios.delete(
      "http://localhost:5027/api/Log/DeleteProductionPlanInfo",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      searchProducts();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};
//跳转修改
const upd = (materialCode: string) => {
  router.push({
    path: "/UpdateProductionplanworkorder",
    query: {
      materialCode: materialCode,
    },
  });
};
// 生命周期钩子
onMounted(() => {
  searchProducts();
});
</script>

<style scoped>
/* 基础样式 */
.production-plan-container {
  height: 100vh;
  padding: 20px;
  background-color: #f9fafc;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 15px;
}

.search-input {
  width: 300px;
  transition: width 0.3s ease;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

/* 按钮样式 */
.add-button {
  background-color: #409eff;
  color: #fff;
  border-radius: 4px;
}
/* 加载状态 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
</style>